import {  getUserInfo, clearCacheAll } from '../../utils/auth'
import http from '../../utils/http'
import { handleOpenIdBindingToMobile, requestPayment } from '../../utils/wx'
import { showModel, showNotify, showToast, showDialog } from '../../utils/index'

Page({

    /**
     * 页面的初始数据
     */
    data: {
        userInfo: null,

        levels: []
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        // 用户登录信息
        this.setData({ userInfo: getUserInfo() });

        this.getLevelList()
    },

    async getLevelList() {
        let res = await http.get('/api/mall/umsmemberlevel/list')
        console.log(res.data);
        this.setData({ levels: res.data })
    },

    async onBuy(e) {
        let { fee, upgradeLevel } = e.currentTarget.dataset
        const { APPID, userInfo } = getApp().globalData

        if(!userInfo.openid) {
            this.setData({ show: true }); return false;
        }

        wx.showLoading({ title: '正在加载中' })

        // 如果当前会员的级别是普通会员，现升级为VIP会员，需要减去差价
        // if(userInfo.level.level == 2) { // 当前会员为普通会员
        //     if(upgradeLevel.level == 3) {
        //         fee = upgradeLevel.fee - userInfo.level.fee
        //     }
        // }
        console.log(fee);

        // 构建订单数据
        let upgradeParams = {
            memberId: userInfo.id,
            levelId: upgradeLevel.id,
        }
        console.log('构建订单数据==>', upgradeParams);

        // 发送请求 创建订单 获取订单编号
        const res = await http.get('/api/mall/umsmember/upgradeMemberPrep', upgradeParams).catch(function (err) {
            console.log(err);
        })
        console.log('发送请求 创建会员升级支付订单 获取订单编号', res);

        if (res.status) {
            // 微信订单预支付请求体参数
            const upgradePayParams = {
                appid: APPID,
                openid: userInfo.openid,
                outTradeNo: res.data,
                body: '[保美驰]会员升级-' + userInfo.nickname,
                totalFee: fee * 100
            }

            console.log(upgradePayParams);

            // 发起 预支付接口
            http.post(`/api/wx/upgrade/pay/${APPID}/now`, upgradePayParams).then(res => {
                if (res.status) {
                    wx.hideLoading()
                    // 发起 微信支付
                    requestPayment(res.data).then(res => {
                        const { errMsg } = res
                        if (errMsg === 'requestPayment:ok') {
                            console.log(res);
                            wx.showModal({
                                title: '提示',
                                content: '会员升级成功，请重新登录',
                                showCancel: false,
                                success(res) {
                                    if (res.confirm) {
                                        clearCacheAll()
                                        wx.switchTab({
                                            url: '/pages/user/user'
                                        })
                                    }
                                }
                            })
                        } else {
                            wx.hideLoading()
                            console.log('订单支付失败[' + errMsg + ']');
                        }
                    }).catch(function (err) {
                        wx.hideLoading()
                        console.log('调起微信支付失败：', err);

                        if (err.errMsg === 'requestPayment:fail cancel') {
                            console.log('用户取消支付');
                        }
                        if (err.errMsg === 'requestPayment:fail no permission') {
                            console.log('title: 未开通支付权限[' + err.errMsg + ']');
                        }
                    })

                } else {
                    wx.hideLoading()
                    console.log('发起微信支付', res.msg);
                }
            })
        }


    },

    /**
     * 微信支付需会员与openid绑定
     * @param {*} e 
     */
     async getUserInfo(e) {
        const userInfo = await handleOpenIdBindingToMobile(e);
        if (userInfo) {
            if(userInfo.openid) {
                showToast({title: '会员与openid绑定：成功'}); return false;
            }
        } else {
            console.log('会员与openid绑定：失败');
            this.setData({ show: true })
        }
    },
})